{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Example 5: Making use of PyRTL and Introspection."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The following example shows how pyrtl can be used to make some interesting\n",
    "hardware structures using **python introspection**.  In particular, this example\n",
    "makes a **N-stage pipeline structure**.  Any specific pipeline is then a derived\n",
    "class of *SimplePipeline* where methods with names starting with *\"stage\"* are\n",
    "stages, and new members with names not starting with \"\\_\" are to be registered\n",
    "for the next stage."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Pipeline builder with auto generation of pipeline registers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import pyrtl\n",
    "\n",
    "pyrtl.reset_working_block()\n",
    "\n",
    "class SimplePipeline(object):\n",
    "    def __init__(self):\n",
    "        self._pipeline_register_map = {}\n",
    "        self._current_stage_num = 0\n",
    "        stage_list = [method for method in dir(self) if method.startswith('stage')]\n",
    "        for stage in sorted(stage_list):\n",
    "            stage_method = getattr(self, stage)\n",
    "            stage_method()\n",
    "            self._current_stage_num += 1\n",
    "    \n",
    "    def __getattr__(self, name):\n",
    "        try:\n",
    "            return self._pipeline_register_map[self._current_stage_num][name]\n",
    "        except KeyError:\n",
    "            raise pyrtl.PyrtlError(\n",
    "                'error, no pipeline register \"%s\" defined for stage %d'\n",
    "                % (name, self._current_stage_num))\n",
    "\n",
    "    def __setattr__(self, name, value):\n",
    "        if name.startswith('_'):\n",
    "            # do not do anything tricky with variables starting with '_'\n",
    "            object.__setattr__(self, name, value)\n",
    "        else:\n",
    "            next_stage = self._current_stage_num + 1\n",
    "            pipereg_id = str(self._current_stage_num) + 'to' + str(next_stage)\n",
    "            rname = 'pipereg_' + pipereg_id + '_' + name\n",
    "            new_pipereg = pyrtl.Register(bitwidth=len(value), name=rname)\n",
    "            if next_stage not in self._pipeline_register_map:\n",
    "                self._pipeline_register_map[next_stage] = {}\n",
    "            self._pipeline_register_map[next_stage][name] = new_pipereg\n",
    "            new_pipereg.next <<= value    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### A very simple pipeline to show how registers are inferred."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "class SimplePipelineExample(SimplePipeline):\n",
    "    def __init__(self):\n",
    "        self._loopback = pyrtl.WireVector(1, 'loopback')\n",
    "        super(SimplePipelineExample, self).__init__()\n",
    "\n",
    "    def stage0(self):\n",
    "        self.n = ~ self._loopback\n",
    "\n",
    "    def stage1(self):\n",
    "        self.n = self.n\n",
    "\n",
    "    def stage2(self):\n",
    "        self.n = self.n\n",
    "\n",
    "    def stage3(self):\n",
    "        self.n = self.n\n",
    "\n",
    "    def stage4(self):\n",
    "        self._loopback <<= self.n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Simulation of the core"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "simplepipeline = SimplePipelineExample()\n",
    "\n",
    "sim_trace = pyrtl.SimulationTrace()\n",
    "sim = pyrtl.Simulation(tracer=sim_trace)\n",
    "\n",
    "for cycle in range(15):\n",
    "    sim.step({})\n",
    "sim_trace.render_trace()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
